var rp = require('request-promise');
const {md5,secretKey} = require("../utils/salt");
const {target} = require("../utils/options");
const jwt = require("jsonwebtoken");
//注册
const reg = async ({ username, password })=>{//更改命名，按语义命名
    const newPWD =  md5(password);
    var options = {
        method: 'POST',
        uri: `${target}/users/reg`,//路径按实际自行添加
        body: {
            username,
            password:newPWD
        },
        json: true // Automatically stringifies the body to JSON
    };
    
   return await rp(options)
}
//登录
const login = async ({ username, password })=>{//更改命名，按语义命名
    const newPWD =  md5(password);
    var options = {
        method: "GET",
        uri: `${target}/users/login`,//路径按实际自行添加
        qs: {
            username,password:newPWD // -> uri + '?access_token=xxxxx%20xxxxx'
        },
        headers: {
            'User-Agent': 'Request-Promise'
        },
        json: true // Automatically parses the JSON string in the response
    };
    
   return await rp(options)
}
//验证用户名
const isUse = async ({ username })=>{//更改命名，按语义命名
    var options = {
        method: 'POST',
        uri: `${target}/users/isUse`,//路径按实际自行添加
        body: {
            username 
        },
        json: true // Automatically stringifies the body to JSON
    };
    
   return await rp(options)
}

const generatorToken = (username,password)=>{
    const payload = {
        username,
        password
        };
        return jwt.sign(
        payload,
        secretKey,
        {
        // expiresIn: 5 // 秒
        expiresIn: 60 * 60 * 24 * 7// 秒
        }
        );
}

module.exports = {reg,login,isUse,generatorToken}